package com.springboot.email.email.service.impl;

import com.springboot.email.email.service.IExportService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class ExportServiceImpl implements IExportService {
    private String encoding;
    private String exportPath = "D:\\export\\";
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    public Template getTemplate(String name) throws Exception {
        return freeMarkerConfigurer.getConfiguration().getTemplate("test.html");
    }


    @Override
    public void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {
        //如果目录不存在，则创建目录
        File exportDirs = new File(exportPath);
        if (!exportDirs.exists()) {
            exportDirs.mkdirs();
        }
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));
        getTemplate(tplName).process(data, writer);
    }

    @Override
    public void exportDocToClient(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment; filename=" +  URLEncoder.encode(fileName , "UTF-8"));
        // 把本地文件发送给客户端
        Writer out = response.getWriter();
        Template template = getTemplate(tplName);
        template.process(data, out);
        out.close();
    }
}
